#include <stdio.h>
#include "04_mqtt.h"

#define USERNAME "zGHFQz4TAK"
#define PASSWORD "version=2018-10-31&res=products%2FzGHFQz4TAK%2Fdevices%2FFirst_device&et=1708506893&method=md5&sign=upLaFHBaMXNNNfUApQSi5Q%3D%3D" 

// 发送成功后回调函数
void delivered(void *context, MQTTClient_deliveryToken dt)
{
	printf("Message with token value %d delivery confirmed\n", dt);
	deliveredtoken = dt;
}

// 接收到消息的回调函数
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
	int i;
	char* payloadptr;

	printf("Message arrived\n");
	printf("     topic: %s\n", topicName);
	printf("   message: ");

	payloadptr = (char*)message->payload;
	for(i=0; i<message->payloadlen; i++)
	{
		putchar(*payloadptr++);
	}

	putchar('\n');
	MQTTClient_freeMessage(&message);
	MQTTClient_free(topicName);
	return 1;
}

// 掉线后的回调函数
void connlost(void *context, char *cause)
{

	printf("\nConnection lost\n");
	printf("     cause: %s\n", cause);

}

int main(void)
{
	mqtt_connect(USERNAME, PASSWORD, connlost, msgarrvd, delivered);
    int i = 20;
    double smoke = 0;
    int humi =0;
    int temp = 0 ;
    srand(time(NULL));

    while(i--)																		//循环发送20次数据
    {
        smoke  = rand() % 10000 / 100.0;
        humi = rand() % 10 + 20;
        temp = rand() % 10 + 20;
		char message[1024] = {0};
		int id =10000;
		sprintf(message, "{\"id\":\"%d\",\"version\":\"1.0\",\"params\":{\"humi\":{\"value\":%d},\"smoke\":{\"value\":%.4f},\"temp\":{\"value\":%d}}}",
				id++, humi, smoke, temp);

		printf("%s\n", message);
		mqtt_send_message(message, id);
		sleep(3);
	}

    MQTTClient_disconnect(client, 10000);										//断开链接
    MQTTClient_destroy(&client);												//销毁客户端
    printf("Hello World!\n");
	//检测程序是否执行到结尾
    return 0;
}

